import utils from '../../../utils/utils'
import { formatTimeDate } from '../../../utils/vutils'
import { EvaluationHttp } from '../../../api/evaluation'
import Dialog from '../../../dist/dialog/dialog';

const evaluationModel = new EvaluationHttp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    evaluationList: [],
    page: 1,
    pageSize: 10,
    totalNum: 0
  },

  initPage () {
    this.httpGetMyAllEvaluation()
  },

  onDeleteEvaluation (event) {
    const { evaluationList } = this.data
    const { id } = event.currentTarget.dataset
    Dialog.confirm({
      message: '确定要删除这条评论吗？'
    }).then(async () => {
      await this.httpDeleteEvaluation(id)
      let index = evaluationList.findIndex(item => item.id === id)
      if (index !== -1) {
        evaluationList.splice(index, 1)
        this.setData({
          evaluationList: evaluationList
        })
      }
    }).catch(() => {
      // on cancel
    });
  },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
    this.setData({
      page: 1
    })
    this.httpGetMyAllEvaluation()
    wx.stopPullDownRefresh()
  },

  // 页面上拉触底事件的处理函数
  onReachBottom: async function () {
    const { evaluationList, page, totalNum } = this.data
    if (evaluationList.length < totalNum) {
      this.setData({
        page: page + 1
      })
      await this.httpGetMyAllEvaluation()
    }
  },

  httpDeleteEvaluation(id) {
    return evaluationModel.deleteEvaluation({
      commentId: id // 评论id
    }).then((res) => {
      utils.msg('删除成功')
    })
  },

  // 获取我的所有评论
  httpGetMyAllEvaluation () {
    const { evaluationList, page, pageSize } = this.data
    return evaluationModel.getMyAllEvaluation({
      pageNo: page,
      pageSize: pageSize
    }).then ((res) => {
      let resMap = []
      if (res.list && res.list.length) {
        resMap = res.list.map(item => {
          return {
            id: item.id, // 评价id
            storeName: item.storeName, // 店铺名称
            storeLogo: item.storeAvatar, // 店铺logo
            createTime: formatTimeDate(new Date(item.createTime * 1000), 'yyyy-MM-dd'), // 评价创建时间
            text: item.comment, // 评价文本
            imgs: item.pictures, // 评价图片
            storeRate: item.storeScore, // 店铺评分
            isDistributionSatisfy: item.deliverScore && item.deliverScore === 1 // 配送评分" 0:不满意， 1:满意
          }
        })
      }
      this.setData({
        evaluationList: page === 1 ? resMap : evaluationList.concat(resMap),
        totalNum: res.total
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})